package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.*;
import com.sky.service.OrdersService;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        //从add表中取数据取数据方法：用参数接收 =Mapper.GetbyId(dto.add number)
        //把这个id的所有数据都取出来了 其中包括phonenumber
        AddressBook addressBook= addressBookMapper.getById(dto.getAddressBookId());
        //判电话号码为空不可下单
        if(addressBook.getPhone()==null){
            throw new RuntimeException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 用User表查下单人
        User user = userMapper.selectById(BaseContext.getCurrentId()); // 使用注入的userMapper实例调用方法
        if (user == null) {
            throw new RuntimeException(MessageConstant.PHONE_IS_NULL);
        }
        //1.构造订单数据存入orders
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        orders.setNumber((System.currentTimeMillis()+""));
            //逻辑判断 刚下单应该是待支付状态      * 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
            //手机号从地址表抽出来、把地址表重写AUTOwried即可
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserName(user.getName());//下单人要用user表查
        orders.setConsignee(addressBook.getConsignee());
        //存表
        ordersMapper.insert(orders);
        //2.明细数据存入order_detail
        List<OrderDetail> ordersDetails = new ArrayList<>();
            //遍历购物车数据
        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (OrderDetail cart : orderDetailList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        //3.删除购物车内容
        shoppingCartMapper.delete(BaseContext.getCurrentId());


        //通过websocket 添加下单提醒
        Map map=new HashMap<>();
        map.put("type","1");
        map.put("orderId",orders.getId());
        map.put("content","订单号为："+orders.getNumber());
        //构造json格式
        String json = JSON.toJSONString(map);
        //通过websocket发送json数据
        //sendToAllClient是在websocket中定义的群发消息方法
        webSocketServer.sendToAllClient(json);


        //4.构造VO返回
        return OrderSubmitVO.builder()
                //VO内部构造
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())

                .build();
    }
    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        //查询订单
        Orders orders = ordersMapper.getById(id);
        //判断空？ 不是空就催单 空则报错
        if (orders == null){
            throw new RuntimeException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map=new HashMap<>();
        map.put("type","2");
        map.put("orderId",orders.getId());
        map.put("content","订单号为："+orders.getNumber()+"的订单，已下单成功");
        String json = JSON.toJSONString(map);
        //使用websocket发送消息
        webSocketServer.sendToAllClient(json);

    }
}
